package Parser;

import java.util.regex.*;

public class Rule {
	private String title;
	private String body;
	
	public Rule() {
		
	}
	
	public Rule(String ruleText) {
		String[] titleBody = ruleText.split(":");
		this.title = titleBody[0].trim();
		this.body = titleBody[1].trim();
	}
	
	public String getElement(int num) {
		String[] elements = body.split(" ");
		return elements[num];
	}
	
	public void setElement(int num, String string) {
		String[] elements = body.split(" ");
		CharSequence replaced = elements[num];
		CharSequence replacer = string;
		this.body = this.body.replace(replaced, replacer);
	}
	
	public boolean isNonTerminal(String element) {
		return isNonTerminal("\\<.+\\>", element);
	}
	
	public static boolean isNonTerminal(String nonTerminalRegex, String element) {
		Pattern nonTerminalPattern = Pattern.compile(nonTerminalRegex);
		Matcher matcher = nonTerminalPattern.matcher(element);
		
		if(matcher.matches()) {
			return true;
		}
		
		return false;
	}
	
	/** Return index of EMPTYSTRING if it is a member of the body,
	 *  otherwise returns -1
	 * XXX: Isn't the EMPTYSTRING (if it is in the body) 
	 *      always at the end? Because I'm not 100% on this,
	 *      I will implement it this way until someone 
	 *      can verify. Otherwise this could be a one-liner
	 *      that returns a boolean:
	 *      	return Parser.EMPTY_STRING.equals(body.split(" ")[body.split(" ").length-1]);
	 *      or
	 *      	Something with regexes
	 * @return
	 */
	public int containsEmptyString() {
		String [] elements = body.split(" ");
		for(int i = 0; i < elements.length; i++) {
			if(Parser.EMPTY_STRING.equals(elements[i])) {
				return i;
			}
		}
		
		return -1;
	}
	
	public int getBodySize() {
		return body.split(" ").length;
	}
	
	public String [] bodyToStringArray() {
		return body.split(" ");
	}
	
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}
	
	public String toString() {
		String string = this.getTitle() + " : "  + this.getBody();
		return string;
	}
}
